/**
 * The scores package of the application.
 */
package fr.umlv.m2.android.quizz.scores;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import fr.umlv.m2.android.quizz.ListSeparerAdapter;
import fr.umlv.m2.android.quizz.R;
import fr.umlv.m2.android.quizz.database.Level;
import fr.umlv.m2.android.quizz.database.LevelDb;

/**
 * This class defines multiplayer tab content of scores part.
 * 
 * @author Gambouele Bertrand.
 * @author Viravout Alexandre.
 */
public class ScoresMultiplayerTabActivity extends Activity {
	/**
	 * The database level object.
	 */
	private LevelDb levelDb;
	
	/**
	 * Create the scores multiplayer tab activity.
	 */
	public ScoresMultiplayerTabActivity() {
		this.levelDb = new LevelDb(this);
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		this.levelDb.open();
		
		final List<Map<String, ?>> levels = new LinkedList<Map<String,?>>();
		for(Level level : levelDb.getAllLevels()) {
			levels.add(createItem(
					level.getName(),
					level.getNbQuestion() + " questions",
					R.drawable.multiplayer)		
			);
		}
		this.levelDb.close();
		
		ListSeparerAdapter adapter = new ListSeparerAdapter(this);
		adapter.addSection(
				this.getResources().getString(R.string.scoresHeaderList), 
				new SimpleAdapter(
					this.getBaseContext(),
					levels,
					R.layout.list,
					new String[] {
						ScoresActivity.ITEM_IMAGE, ScoresActivity.ITEM_TITLE, ScoresActivity.ITEM_SUBTITLE
					},
					new int[] { R.id.list_image, R.id.list_title, R.id.list_subtitle }
				)
		);
		
		final ListView list = new ListView(this);
		list.setAdapter(adapter);
		this.setContentView(list);
		
		list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Intent intent = new Intent(ScoresMultiplayerTabActivity.this, ScoresMultiplayerByLevelActivity.class);
				
				@SuppressWarnings("unchecked")
				Map<String, ?> levelItem = (Map<String, ?>)parent.getItemAtPosition(position);
				String levelName = (String)levelItem.get("title");
				
				levelDb.open();
				Level level = levelDb.getLevelWithName(levelName);
				levelDb.close();
				
				intent.putExtra("levelId", level.getId());
				startActivity(intent);
			}
		});
	}
	
	private Map<String, ?> createItem(String title, String subtitle, int image) {
		Map<String, String> item = new HashMap<String, String>();
		
		item.put(ScoresActivity.ITEM_IMAGE, String.valueOf(image));
		item.put(ScoresActivity.ITEM_TITLE, title);
		item.put(ScoresActivity.ITEM_SUBTITLE, subtitle);
		
		return item;
	}
}
